import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { 
  ArrowLeft,
  Package, 
  Clock, 
  Truck, 
  CheckCircle, 
  XCircle,
  MapPin,
  CreditCard,
  Phone,
  User
} from 'lucide-react';
import { orderApi } from '@/db/api';
import { useAuth } from 'miaoda-auth-react';
import type { Order } from '@/types/types';
import { toast } from 'sonner';

const OrderDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    
    if (id) {
      loadOrder();
    }
  }, [user, id, navigate]);

  const loadOrder = async () => {
    try {
      setLoading(true);
      const data = await orderApi.getOrder(id!);
      if (data) {
        setOrder(data);
      } else {
        toast.error('订单不存在');
        navigate('/orders');
      }
    } catch (error) {
      console.error('加载订单失败:', error);
      toast.error('加载订单失败');
      navigate('/orders');
    } finally {
      setLoading(false);
    }
  };

  const getStatusInfo = (status: Order['status']) => {
    switch (status) {
      case 'pending':
        return {
          label: '待付款',
          color: 'bg-yellow-100 text-yellow-800',
          icon: Clock,
          description: '请在24小时内完成付款，超时订单将自动取消'
        };
      case 'paid':
        return {
          label: '已付款',
          color: 'bg-blue-100 text-blue-800',
          icon: Package,
          description: '您的订单已付款成功，我们将尽快为您发货'
        };
      case 'shipped':
        return {
          label: '已发货',
          color: 'bg-purple-100 text-purple-800',
          icon: Truck,
          description: '您的订单已发货，请注意查收'
        };
      case 'delivered':
        return {
          label: '已完成',
          color: 'bg-green-100 text-green-800',
          icon: CheckCircle,
          description: '订单已完成，感谢您的购买'
        };
      case 'cancelled':
        return {
          label: '已取消',
          color: 'bg-red-100 text-red-800',
          icon: XCircle,
          description: '订单已取消'
        };
      default:
        return {
          label: '未知',
          color: 'bg-gray-100 text-gray-800',
          icon: Package,
          description: ''
        };
    }
  };

  const getPaymentMethodName = (method: string) => {
    switch (method) {
      case 'wechat':
        return '微信支付';
      case 'alipay':
        return '支付宝';
      case 'bank':
        return '银行卡支付';
      case 'cod':
        return '货到付款';
      default:
        return method;
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-pink-600"></div>
      </div>
    );
  }

  if (!order) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">订单不存在</h2>
          <Button onClick={() => navigate('/orders')}>返回订单列表</Button>
        </div>
      </div>
    );
  }

  const statusInfo = getStatusInfo(order.status);
  const StatusIcon = statusInfo.icon;

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="flex items-center gap-4 mb-8">
          <Button variant="ghost" onClick={() => navigate('/orders')}>
            <ArrowLeft className="h-5 w-5 mr-2" />
            返回订单列表
          </Button>
          <h1 className="text-3xl font-bold text-gray-900">订单详情</h1>
        </div>

        <div className="space-y-6">
          {/* Order Status */}
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className={`p-3 rounded-full ${statusInfo.color.replace('text-', 'bg-').replace('800', '200')}`}>
                    <StatusIcon className="h-6 w-6" />
                  </div>
                  <div>
                    <h2 className="text-xl font-semibold">{statusInfo.label}</h2>
                    <p className="text-gray-600">{statusInfo.description}</p>
                  </div>
                </div>
                <Badge className={statusInfo.color}>
                  {statusInfo.label}
                </Badge>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
                <div>订单号: {order.order_number}</div>
                <div>下单时间: {new Date(order.created_at).toLocaleString()}</div>
              </div>
            </CardContent>
          </Card>

          {/* Order Items */}
          <Card>
            <CardHeader>
              <CardTitle>商品信息</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {order.order_items?.map((item) => (
                <div key={item.id} className="flex items-center gap-4 p-4 border rounded-lg">
                  <div className="w-20 h-20 flex-shrink-0 overflow-hidden rounded-lg">
                    <img
                      src={item.product_image || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=200'}
                      alt={item.product_name}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div className="flex-1">
                    <h3 className="font-semibold text-gray-900">{item.product_name}</h3>
                    <div className="text-sm text-gray-500 mt-1">
                      {item.size && `尺码: ${item.size} `}
                      {item.color && `颜色: ${item.color}`}
                    </div>
                    <div className="flex items-center justify-between mt-2">
                      <span className="text-sm text-gray-600">数量: {item.quantity}</span>
                      <span className="font-semibold text-pink-600">
                        ¥{(item.price * item.quantity).toFixed(2)}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>

          {/* Shipping Address */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <MapPin className="h-5 w-5" />
                收货地址
              </CardTitle>
            </CardHeader>
            <CardContent>
              {order.shipping_address ? (
                <div className="space-y-2">
                  <div className="flex items-center gap-2">
                    <User className="h-4 w-4 text-gray-500" />
                    <span className="font-medium">{order.shipping_address.name}</span>
                    <Phone className="h-4 w-4 text-gray-500 ml-4" />
                    <span>{order.shipping_address.phone}</span>
                  </div>
                  <div className="text-gray-600">
                    {order.shipping_address.province} {order.shipping_address.city} {order.shipping_address.district}
                  </div>
                  <div className="text-gray-600">
                    {order.shipping_address.address}
                  </div>
                  {order.shipping_address.postal_code && (
                    <div className="text-sm text-gray-500">
                      邮编: {order.shipping_address.postal_code}
                    </div>
                  )}
                </div>
              ) : (
                <div className="text-gray-500">暂无收货地址信息</div>
              )}
            </CardContent>
          </Card>

          {/* Payment & Order Info */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Payment Info */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <CreditCard className="h-5 w-5" />
                  支付信息
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-gray-600">支付方式</span>
                  <span>{getPaymentMethodName(order.payment_method || '')}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">商品总价</span>
                  <span>¥{order.total_amount.toFixed(2)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">运费</span>
                  <span className="text-green-600">免费</span>
                </div>
                <Separator />
                <div className="flex justify-between text-lg font-bold">
                  <span>实付金额</span>
                  <span className="text-pink-600">¥{order.total_amount.toFixed(2)}</span>
                </div>
              </CardContent>
            </Card>

            {/* Order Notes */}
            <Card>
              <CardHeader>
                <CardTitle>订单备注</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-gray-600">
                  {order.notes || '无备注'}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Action Buttons */}
          <Card>
            <CardContent className="p-6">
              <div className="flex gap-4 justify-end">
                {order.status === 'pending' && (
                  <>
                    <Button variant="outline">
                      取消订单
                    </Button>
                    <Button className="bg-pink-600 hover:bg-pink-700">
                      立即付款
                    </Button>
                  </>
                )}
                
                {order.status === 'shipped' && (
                  <Button className="bg-pink-600 hover:bg-pink-700">
                    确认收货
                  </Button>
                )}
                
                {order.status === 'delivered' && (
                  <Button variant="outline">
                    评价商品
                  </Button>
                )}
                
                <Button variant="outline">
                  联系客服
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default OrderDetail;